<template>
  <div id="login-container">
    <div id="login-box">
      <div id="avatar-box">
        <img src="../assets/logo.png" alt="" />
      </div>

      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username">
            <i slot="prefix" class="iconfont icon-user"></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" show-password>
            <i slot="prefix" class="iconfont icon-3702mima"></i>
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :push="15">
            <el-button type="primary" @click="login()">登录</el-button>
            <el-button type="info" @click="$refs.loginFormRef.resetFields()"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    //用户登陆系统
    login() {
      //对登陆的from表单进行整体校验
      this.$refs.loginFormRef.validate(async valid => {
        if (valid == true) {
          //axios刚问服务器校验用户名和密码是否有效
          const { data: res } = await this.$http.post("/login", this.loginForm);
          if (res.meta.status !== 200) {
            return this.$http.error("用户名或密码不存在");
          }

          //通过浏览器的sessionStorage记录服务器返回的token信息
          window.sessionStorage.setItem("token", res.data.token);
          this.$router.push("/home");
        }
      });
    }
  },
  data() {
    return {
      //from表单数据对象
      loginForm: {
        username: "",
        password: ""
      },
      //表单校验规则定义
      loginFormRules: {
        username: [{ required: true, message: "用户名必填", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  }
};
</script>
<style lang="less" scoped>
#login-container {
  background-color: #2b4b6b;
  height: 100%;
  overflow: hidden;
  #login-box {
    width: 450px;
    height: 304px;
    background-color: #fff;
    border-radius: 4px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%;-50%);
    .el-form {
      position: absolute;
      bottom: 0px;
      width: 100%;
      padding: 20px;
      box-sizing: border-box;
    }
    #avatar-box {
      width: 130px;
      height: 130px;
      border-radius: 50%;
      border: 1px solid #eee;
      padding: 8px;
      box-shadow: 0 0 10px #eee;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #fff;
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: #eee;
      }
    }
  }
}
</style>
